package com.frame.project.service.system.user.imp;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.frame.common.constant.UserConstants;
import com.frame.common.enumutil.RemoveEnum;
import com.frame.common.exception.BusinessException;
import com.frame.common.exception.ServiceException;
import com.frame.common.utils.StringUtils;
import com.frame.common.utils.page.MyPage;
import com.frame.common.utils.security.ShiroUtils;
import com.frame.common.utils.spring.SpringUtils;
import com.frame.common.utils.text.Convert;
import com.frame.framework.aspectj.DataScopeAspect;
import com.frame.framework.aspectj.lang.annotation.DataScope;
import com.frame.framework.shiro.service.PasswordService;
import com.frame.framework.web.error.WebError;
import com.frame.framework.web.service.imp.AbstractBaseService;
import com.frame.project.domain.system.dept.Dept;
import com.frame.project.domain.system.post.Post;
import com.frame.project.domain.system.role.Role;
import com.frame.project.domain.system.user.User;
import com.frame.project.domain.system.user.UserPost;
import com.frame.project.domain.system.user.UserRole;
import com.frame.project.repository.system.user.UserRepository;
import com.frame.project.service.system.config.IConfigService;
import com.frame.project.service.system.dept.DeptService;
import com.frame.project.service.system.post.PostService;
import com.frame.project.service.system.role.RoleService;
import com.frame.project.service.system.user.UserPostService;
import com.frame.project.service.system.user.UserRoleService;
import com.frame.project.service.system.user.UserService;

/**
 * 
 * @className ：UserServiceImpl
 * @describe ：用户
 */
@Service
public class UserServiceImpl extends AbstractBaseService<User> implements UserService{

	private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
	
	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private RoleService RoleService; 
	
	@Autowired
	private PostService postService;
	
	@Autowired
	private DeptService deptService;
	
	@Autowired
	private UserPostService userPostService;
	
	@Autowired
	private UserRoleService userRoleService;
	
	@Autowired
	private IConfigService configService;
	
	@Autowired
    private PasswordService passwordService;
	
	@PersistenceContext
	private EntityManager em;
	
	/**
	 * 分页
	 */
	@Override
	@DataScope(deptAlias = "d", userAlias = "u")
	public MyPage<User> findByPage(User user, Integer pageNo, Integer pageSize) {
		StringBuilder sql = new StringBuilder(
                "select u.id, u.dept_id, u.login_name, u.user_name, u.email, u.avatar, u.phone_number, u.password, u.sex, u.status, u.remove_status as removeStatus, u.login_ip as loginIp, u.login_date, u.create_by, u.create_time, u.remark, d.dept_name as deptName, d.leader from sys_user u" +
                        " left join sys_dept d on u.dept_id = d.id" +
                        " where u.remove_status = '0'");
        if(user.getId() != null){
            sql.append(" and u.id = ").append(user.getId());
        }
        if(StringUtils.isNotBlank(user.getUserName())){
            sql.append(" and u.user_name like concat('%','").append(user.getUserName()).append("', '%')");
        }
        if(StringUtils.isNotBlank(user.getStatus())){
            sql.append(" and u.status = ").append(user.getStatus());
        }
        if(StringUtils.isNotBlank(user.getPhonenumber())){
            sql.append(" and u.phonenumber like concat('%',").append(user.getPhonenumber()).append(", '%')");
        }
        if(user.getDeptId() != null){
            sql.append(" and (u.dept_id = ").append(user.getDeptId()).append(" or u.dept_id in ( select t.id from sys_dept t where find_in_set(").append(user.getDeptId()).append(", ancestors) ))");
        }

        if(user.getParams() != null){
            Map<String, Object> params = user.getParams();
            String beginTime = (String) params.get("beginTime");
            String endTime = (String) params.get("endTime");
            String sqlString = (String)params.get(DataScopeAspect.DATA_SCOPE);

            if(StringUtils.isNotBlank(beginTime)){
                sql.append(" and date_format(r.create_time,'%y%m%d') >= date_format('").append(beginTime).append("','%y%m%d')");
            }
            if(StringUtils.isNotBlank(endTime)){
                sql.append(" and date_format(r.create_time,'%y%m%d') <= date_format('").append(endTime).append("','%y%m%d')");
            }
            if(StringUtils.isNotBlank(sqlString)){
                sql.append(sqlString);
            }
        }
        System.out.println(sql.toString());
        Query query = em.createNativeQuery(sql.toString());
        int firstIndex = pageNo * pageSize;
        query.setFirstResult(firstIndex);
        query.setMaxResults(pageSize);
        List<Object[]> list = query.getResultList();
        String countSql = "select count(*) from ("+sql.toString()+") c";
        Query countQuery = em.createNativeQuery(countSql);
        Object obj = countQuery.getSingleResult();
        Integer tatal = Integer.parseInt(obj.toString());
        BigDecimal bd = BigDecimal.valueOf(tatal);
        BigDecimal bdsize = BigDecimal.valueOf(pageSize);
        BigDecimal bdvi = bd.divide(bdsize, 1, BigDecimal.ROUND_HALF_UP);
        Integer totalPage = (int)Math.ceil(bdvi.doubleValue());
        List<User> userList = new ArrayList<User>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for(Object[] objects : list){
        	User u = new User();
            u.setId(Long.parseLong(objects[0].toString()));
            u.setDeptId(objects[1] == null ? null : Long.parseLong(objects[1].toString()));
            u.setLoginName(objects[2].toString());
            u.setUserName(objects[3].toString());
            u.setEmail(objects[4].toString());
            u.setAvatar(objects[5] == null ? "" : objects[5].toString());
            u.setPhonenumber(objects[6].toString());
            u.setSex(objects[8].toString());
            u.setStatus(objects[9].toString());
            u.setRemoveStatus(objects[10] == null ? null : Integer.parseInt(objects[10].toString()));
            u.setLoginIp(objects[11] == null ? "" : objects[11].toString());

            try {
            	u.setLoginDate(objects[12] == null ? null : format.parse(objects[12].toString()));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
            	u.setCreateTime(objects[14] == null ? null : format.parse(objects[14].toString()));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Dept sd = new Dept();
            sd.setDeptName(objects[16] == null ? "" : objects[16].toString());
            sd.setLeader(objects[17] == null ? "" : objects[17].toString());
            u.setDept(sd);
            userList.add(u);
        }
        MyPage<User> page = new MyPage<User>(pageNo,totalPage,userList,new  com.frame.common.utils.page.Pageable(pageSize),tatal+"",tatal);
        return page;
	}
	
	/**
     * 根据条件分页查询已分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public MyPage<User> selectAllocatedList(User user, Integer pageNo, Integer pageSize)
    {
    	StringBuilder sql = new StringBuilder(
				"select distinct u.id, u.dept_id, u.login_name, u.user_name, u.email, u.avatar, u.phone_number, u.status, u.create_time"
				+ " from sys_user u"
				+ " left join sys_dept d on u.dept_id = d.id"
				+ " left join sys_user_role ur on u.id = ur.user_id"
				+ " left join sys_role r on r.id = ur.role_id where 1 = 1");
    	sql.append(" and u.remove_status =").append(RemoveEnum.NOT_REMOVE.getCode());
    	
    	if(user.getRoleId() != null) {
    		sql.append(" and r.id = ").append(user.getRoleId());
    	}
    	
    	if(StringUtils.isNotBlank(user.getLoginName())) {
    		sql.append(" and u.login_name like concat('%', ").append(user.getLoginName()).append(", '%')");
    	}
    	
    	if(StringUtils.isNotBlank(user.getPhonenumber())) {
    		sql.append(" and u.phone_number like concat('%', ").append(user.getPhonenumber()).append(", '%')");
    	}
    	
    	if(user.getParams() != null){
            Map<String, Object> params = user.getParams();
            String sqlString = (String)params.get(DataScopeAspect.DATA_SCOPE);

            if(StringUtils.isNotBlank(sqlString)){
                sql.append(sqlString);
            }
        }
    	
    	Query query = em.createNativeQuery(sql.toString());
		int firstIndex = pageNo * pageSize;
	    query.setFirstResult(firstIndex);
	    query.setMaxResults(pageSize);
	    List<Object[]> list = query.getResultList();
	    String countSql = "select count(*) from ("+sql.toString()+") c";
	    Query countQuery = em.createNativeQuery(countSql);
	    Object obj = countQuery.getSingleResult();
	    Integer tatal = Integer.parseInt(obj.toString());
	    BigDecimal bd = BigDecimal.valueOf(tatal);
	    BigDecimal bdsize = BigDecimal.valueOf(pageSize);
	    BigDecimal bdvi = bd.divide(bdsize, 1, BigDecimal.ROUND_HALF_UP);
	    Integer totalPage = (int)Math.ceil(bdvi.doubleValue());
	    List<User> list1 = new ArrayList<User>();
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	    for(Object[] objects : list) {
	    	User u = new User();
	    	
	    	u.setId(Long.parseLong(objects[0].toString()));
	    	u.setDeptId(objects[1] == null ? null : Long.parseLong(objects[1].toString()));
	    	u.setLoginName(objects[2].toString());
	    	u.setUserName(objects[3].toString());
	    	u.setEmail(objects[4].toString());
	    	u.setAvatar(objects[5].toString());
	    	u.setPhonenumber(objects[6].toString());
	    	u.setStatus(objects[7].toString());
	    	try {
				u.setCreateTime(format.parse(objects[8].toString()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	list1.add(u);
	    }
	    
	    MyPage<User> page = new MyPage<User>(pageNo,totalPage,list1,new com.frame.common.utils.page.Pageable(pageSize),tatal+"",tatal);
	    return page;
    }
    
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public MyPage<User> selectUnallocatedList(User user, Integer pageNo, Integer pageSize)
    {
    	StringBuilder sql = new StringBuilder(
				"select distinct u.id, u.dept_id, u.login_name, u.user_name, u.email, u.avatar, u.phone_number, u.status, u.create_time"
				+ " from sys_user u"
				+ " left join sys_dept d on u.dept_id = d.id"
				+ " left join sys_user_role ur on u.id = ur.user_id"
				+ " left join sys_role r on r.id = ur.role_id where 1 = 1");
    	sql.append(" and u.remove_status =").append(RemoveEnum.NOT_REMOVE.getCode());
    	
    	if(StringUtils.isNotNull(user.getRoleId())) {
    		sql.append(" and u.id not in (select u.id from sys_user u inner join sys_user_role ur on u.id = ur.user_id and ur.role_id = ").append(user.getRoleId()).append(")");
    	}
    	
    	if(StringUtils.isNotBlank(user.getLoginName())) {
    		sql.append(" and u.login_name like concat('%', ").append(user.getLoginName()).append(", '%')");
    	}
    	
    	if(StringUtils.isNotBlank(user.getPhonenumber())) {
    		sql.append(" and u.phone_number like concat('%', ").append(user.getPhonenumber()).append(", '%')");
    	}
    	
    	if(user.getParams() != null){
            Map<String, Object> params = user.getParams();
            String sqlString = (String)params.get(DataScopeAspect.DATA_SCOPE);

            if(StringUtils.isNotBlank(sqlString)){
                sql.append(sqlString);
            }
        }
    	Query query = em.createNativeQuery(sql.toString());
		int firstIndex = pageNo * pageSize;
	    query.setFirstResult(firstIndex);
	    query.setMaxResults(pageSize);
	    List<Object[]> list = query.getResultList();
	    String countSql = "select count(*) from ("+sql.toString()+") c";
	    Query countQuery = em.createNativeQuery(countSql);
	    Object obj = countQuery.getSingleResult();
	    Integer tatal = Integer.parseInt(obj.toString());
	    BigDecimal bd = BigDecimal.valueOf(tatal);
	    BigDecimal bdsize = BigDecimal.valueOf(pageSize);
	    BigDecimal bdvi = bd.divide(bdsize, 1, BigDecimal.ROUND_HALF_UP);
	    Integer totalPage = (int)Math.ceil(bdvi.doubleValue());
	    List<User> list1 = new ArrayList<User>();
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	    for(Object[] objects : list) {
	    	User u = new User();
	    	
	    	u.setId(Long.parseLong(objects[0].toString()));
	    	u.setDeptId(objects[1] == null ? null : Long.parseLong(objects[1].toString()));
	    	u.setLoginName(objects[2].toString());
	    	u.setUserName(objects[3].toString());
	    	u.setEmail(objects[4].toString());
	    	u.setAvatar(objects[5].toString());
	    	u.setPhonenumber(objects[6].toString());
	    	u.setStatus(objects[7].toString());
	    	try {
				u.setCreateTime(format.parse(objects[8].toString()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	list1.add(u);
	    }
	    
	    MyPage<User> page = new MyPage<User>(pageNo,totalPage,list1,new com.frame.common.utils.page.Pageable(pageSize),tatal+"",tatal);
	    return page;
    }
	
    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public User selectUserByLoginName(String userName)
    {
    	User u = userRepository.findByLoginName(userName);
    	List<UserRole> urList = userRoleService.selectUserRoleByUserId(u.getId());
    	List<Role> rList = new ArrayList<Role>();
    	for(UserRole ur : urList) {
    		rList.add(ur.getRole());
    	}
    	u.setRoles(rList);
        return u;
    }
    
    /**
     * 通过手机号码查询用户
     * 
     * @param phoneNumber 手机号码
     * @return 用户对象信息
     */
    @Override
    public User selectUserByPhoneNumber(String phoneNumber)
    {
        return userRepository.findByPhonenumber(phoneNumber);
    }
    
    /**
     * 通过邮箱查询用户
     * 
     * @param email 邮箱
     * @return 用户对象信息
     */
    @Override
    public User selectUserByEmail(String email)
    {
        return userRepository.findByEmail(email);
    }
	
	/**
     * 通过用户ID查询用户和角色关联
     * 
     * @param userId 用户ID
     * @return 用户和角色关联列表
     */
    @Override
    public List<UserRole> selectUserRoleByUserId(Long userId)
    {
        return userRoleService.selectUserRoleByUserId(userId);
    }
    
    /**
     * 通过用户ID删除用户
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public void deleteUserById(Long userId)
    {
        // 删除用户与角色关联
    	userRoleService.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
    	userPostService.deleteUserPostByUserId(userId);
    	
    	userRepository.delete(findById(userId));
    }
    
    /**
     * 批量删除用户信息
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public WebError deleteUserByIds(String ids) throws BusinessException
    {
        Long[] userIds = Convert.toLongArray(ids);
        for (Long userId : userIds)
        {
            WebError web = checkUserAllowed(userId);
            if(web.getCode() == -1) {
            	return web;
            }
        }
        
        for(Long userId : userIds) {
        	deleteUserById(userId);
        }
        
        return new WebError();
    }
    
    /**
     * 新增保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public void insertUser(User user)
    {
        user.randomSalt();
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        if(StringUtils.isNotNull(user.getDeptId())) {
        	user.setDept(deptService.findById(user.getDeptId()));
        }
        user.setAvatar("");
        // 新增用户信息
        add(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user.getId(), user.getRoleIds());
    }
    
    /**
     * 注册用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(User user)
    {
        user.randomSalt();
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setRemoveStatus(RemoveEnum.NOT_REMOVE.getCode());
        user.setCreateTime(new Date());
        
        User save = userRepository.save(user);
        if(save != null) {
        	return true;
        }else {
        	return false;
        }
    }
    
    /**
     * 修改保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public void updateUser(User user)
    {
        User u = findById(user.getId());
        u.setUserName(user.getUserName());
        u.setDeptId(user.getDeptId());
        if(StringUtils.isNotNull(user.getDeptId())) {
        	u.setDept(deptService.findById(user.getDeptId()));
        }
        u.setPhonenumber(user.getPhonenumber());
        u.setEmail(user.getEmail());
        u.setStatus(user.getStatus());
        u.setSex(user.getSex());
        u.setRemark(user.getRemark());
        
        // 删除用户与角色关联
        userRoleService.deleteUserRoleByUserId(user.getId());
        // 新增用户与角色管理
        insertUserRole(user.getId(), user.getRoleIds());
        // 删除用户与岗位关联
        userPostService.deleteUserPostByUserId(user.getId());
        // 新增用户与岗位管理
        insertUserPost(user);
        modify(u);
    }
    
    /**
     * 修改用户个人详细信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean updateUserInfo(User user)
    {
    	User save = userRepository.save(user);
    	if(StringUtils.isNotNull(save)) {
    		return true;
    	}else {
    		return false;
    	}
    }
    
    /**
     * 用户授权角色
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    public void insertUserAuth(Long userId, Long[] roleIds)
    {
    	userRoleService.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }
    
    /**
     * 修改用户密码
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean resetUserPwd(User user)
    {
    	User u = findById(user.getId());
    	u.setPwdUpdateDate(new Date());
        u.randomSalt();
        u.setPassword(passwordService.encryptPassword(u.getLoginName(), user.getPassword(), u.getSalt()));
        return updateUserInfo(u);
    }
    
    /**
     * 校验用户是否允许操作
     * 
     * @param user 用户信息
     */
    @Override
    public WebError checkUserAllowed(Long userId)
    {
    	User u = findById(userId);
        if (StringUtils.isNotNull(userId) && u.isAdmin())
        {
            return new WebError(-1, "不允许操作超级管理员用户");
        }
        
        return new WebError();
    }
    
    /**
     * 校验用户是否有数据权限
     * 
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId)
    {
    	User u = userRepository.findByUserId(ShiroUtils.getUserId());
        if (!User.isAdmin(u.getLoginName()))
        {
            User user = new User();
            user.setId(userId);
            List<User> users = SpringUtils.getAopProxy(this).findByPage(user, 0,Integer.MAX_VALUE).getContent();
            if (StringUtils.isEmpty(users))
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }
    
    /**
     * 新增用户岗位信息
     * 
     * @param user 用户对象
     */
    public void insertUserPost(User user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts))
        {
            // 新增用户与岗位管理
            List<UserPost> list = new ArrayList<UserPost>();
            for (Long postId : user.getPostIds())
            {
                UserPost up = new UserPost();
                up.setUser(findById(user.getId()));
                up.setPost(postService.findById(postId));
                list.add(up);
            }
            if (list.size() > 0)
            {
            	userPostService.batchUserPost(list);
            }
        }
    }
    
    /**
     * 新增用户角色信息
     * 
     * @param user 用户对象
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotNull(roleIds))
        {
            // 新增用户与角色管理
            List<UserRole> list = new ArrayList<UserRole>();
            for (Long roleId : roleIds)
            {
                UserRole ur = new UserRole();
                ur.setUser(findById(userId));
                ur.setRole(RoleService.findById(roleId));
                list.add(ur);
            }
            if (list.size() > 0)
            {
            	userRoleService.batchUserRole(list);
            }
        }
    }
    
    /**
     * 校验登录名称是否唯一
     * 
     * @param loginName 用户名
     * @return
     */
    @Override
    public String checkLoginNameUnique(String loginName)
    {
        int count = userRepository.checkLoginNameUnique(loginName);
        if (count > 0)
        {
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }
    
    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(User user)
    {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        User info = userRepository.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getId() != userId)
        {
            return UserConstants.USER_PHONE_NOT_UNIQUE;
        }
        return UserConstants.USER_PHONE_UNIQUE;
    }
    
    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(User user)
    {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        User info = userRepository.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getId() != userId)
        {
            return UserConstants.USER_EMAIL_NOT_UNIQUE;
        }
        return UserConstants.USER_EMAIL_UNIQUE;
    }
    
    /**
     * 查询用户所属角色组
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(Long userId)
    {
        List<Role> list = RoleService.selectRolesByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (Role role : list)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }
    
    /**
     * 查询用户所属岗位组
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(Long userId)
    {
        List<Post> list = postService.selectPostsByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (Post post : list)
        {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 导入用户数据
     * 
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importUser(List<User> userList, Boolean isUpdateSupport)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new BusinessException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String operName = ShiroUtils.getLoginName();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (User user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                User u = userRepository.findByLoginName(user.getLoginName());
                if (StringUtils.isNull(u))
                {
                    user.setPassword(password);
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getLoginName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getLoginName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    
    /**
     * 用户状态修改
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public void changeStatus(User user)
    {
    	User u = findById(user.getId());
    	u.setStatus(user.getStatus());
    	u.setUpdateBy(ShiroUtils.getLoginName());
        u.setUpdateTime(new Date());
    	userRepository.save(u);
    }
}
